package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.Product;
import csu.web.mypetstore.service.CatalogService;
import csu.web.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class SearchServlet extends HttpServlet {
    private static final String SEARCH = "/WEB-INF/jsp/catalog/search.jsp";
    private String keyword;

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        keyword = req.getParameter("keyword");

        CatalogService service = new CatalogService();

        List<Product> productList = service.searchProductList(keyword);

        HttpSession session = req.getSession();

        session.setAttribute("productList",productList);

        Account account = (Account) session.getAttribute("loginAccount");
        if(account != null) {
            String strUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                    + req.getContextPath() + req.getServletPath() + "?" + req.getQueryString();
            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") +"用户" +account.getUsername()+  "  " + "搜索" + keyword ;
            logService.insertLogInfo(account.getUsername(),logInfo);
        }

        req.getRequestDispatcher(SEARCH).forward(req,resp);
    }
}
